import LRContainer from '@/components/CardLayout/LRContainer';
import SettingGroupModal from '@/pages/system/setting/components/SettingGroupModal';
import {
  addSettingAPI,
  addSettingGroupAPI,
  deleteSettingAPI,
  deleteSettingGroupAPI,
  pageSettingAPI,
  pageSettingGroupAPI,
  updateSettingAPI,
  updateSettingGroupAPI,
} from '@/pages/system/setting/service';
import { fullDownloadFileUrl } from '@/services/system/file';
import { API } from '@/services/typings';
import { DeleteOutlined, DiffOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import SettingDetail from './components/SettingDetail';
import SettingForm from './components/SettingForm';

const SettingManager: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const groupActionRef = useRef<ActionType>();
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentSetting, setCurrentSetting] = useState<API.ISetting | undefined>(undefined);
  const [currentSettingGroup, setCurrentSettingGroup] = useState<API.ISettingGroup | undefined>(
    undefined,
  );

  useEffect(() => {
    actionRef.current?.reload();
  }, [currentSettingGroup]);

  const groupColumns: ProColumns<API.ISettingGroup>[] = [
    {
      title: '分组名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '键值',
      dataIndex: 'groupKey',
      ellipsis: true,
    },
    {
      width: 100,
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a
          key="delete"
          style={{ color: 'red' }}
          onClick={async () => {
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除设置分组项 ${record.name} 吗？`,
              onOk: async () => {
                const { data } = await deleteSettingGroupAPI(record.id || '');
                if (data) {
                  message.success('删除成功');
                  groupActionRef.current?.reload();
                }
                return data;
              },
            });
          }}
        >
          <DeleteOutlined /> 删除
        </a>,
        <SettingGroupModal
          key="update"
          isAdd={false}
          settingGroup={record}
          onSubmit={async (values) => {
            const { data } = await updateSettingGroupAPI({
              ...values,
              id: record.id,
              version: record.version,
            });
            if (data) {
              groupActionRef.current?.reload();
              message.success('添加成功');
            }
            return !!data;
          }}
        />,
      ],
    },
  ];

  const columns: ProColumns<API.ISetting>[] = [
    {
      title: '设置名称',
      dataIndex: 'name',
      width: 150,
      fixed: 'left',
      copyable: true,
    },
    {
      title: '配置键',
      dataIndex: 'settingKey',
      copyable: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '配置类型',
      dataIndex: 'settingType',
      width: 120,
      valueEnum: {
        string: { text: '字符串' },
        number: { text: '数值' },
        boolean: { text: '布尔值' },
        json: { text: 'JSON' },
        file: { text: '文件' },
      },
    },
    {
      title: '配置值',
      dataIndex: 'settingValue',
      width: 200,
      ellipsis: true,
      hideInSearch: true,
      render: (text, record) => {
        if (record.settingType === 'file') {
          return (
            <a
              href={fullDownloadFileUrl(record.settingValue || '')}
              target="_blank"
              rel="noopener noreferrer"
            >
              查看文件
            </a>
          );
        }
        return text;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentSetting(record);
            setDetailVisible(true);
          }}
        >
          <EyeOutlined /> 查看
        </a>,
        <SettingForm
          key="edit"
          trigger={
            <a>
              <EditOutlined /> 编辑
            </a>
          }
          initialValues={record}
          title={`编辑设置 - ${record.name}`}
          onFinish={async (values) => {
            try {
              const { data } = await updateSettingAPI({ ...values, id: record.id });
              if (data) {
                message.success('更新成功');
                actionRef.current?.reload();
              }
              return data;
            } catch (error) {
              message.error('更新失败');
              return false;
            }
          }}
        />,
        <a
          key="delete"
          style={{ color: 'red' }}
          onClick={async () => {
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除设置项 ${record.name} 吗？`,
              onOk: async () => {
                const { data } = await deleteSettingAPI(record.id || '');
                if (data) {
                  message.success('删除成功');
                  actionRef.current?.reload();
                }
                return data;
              },
            });
          }}
        >
          <DeleteOutlined /> 删除
        </a>,
      ],
    },
  ];

  return (
    <LRContainer
      leftTitle="系统设置分组"
      rightTitle="详情"
      leftExtra={[
        <SettingGroupModal
          key="add"
          isAdd={true}
          onSubmit={async (values) => {
            const { data } = await addSettingGroupAPI(values);
            if (data) {
              groupActionRef.current?.reload();
              message.success('添加成功');
            }
            return !!data;
          }}
        />,
      ]}
      rightExtra={
        <Space>
          <SettingForm
            key="create"
            trigger={
              <Button type="primary" icon={<DiffOutlined />}>
                新增设置
              </Button>
            }
            title="新增系统设置"
            onFinish={async (values) => {
              const { data } = await addSettingAPI(values);
              if (data) {
                message.success('添加成功');
                actionRef.current?.reload();
              }
              return data;
            }}
          />
        </Space>
      }
      leftContent={
        <ProTable<API.ISettingGroup>
          columns={groupColumns}
          actionRef={groupActionRef}
          request={async (params) => {
            const { data } = await pageSettingGroupAPI(params);
            return data;
          }}
          tableAlertRender={false}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            span: 6,
            filterType: 'light',
          }}
          pagination={
            {
              pageSize: 10,
            } as any
          }
          onRow={(record: any) => {
            return {
              onClick: () => {
                setCurrentSettingGroup(record);
              },
            };
          }}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: currentSettingGroup ? [currentSettingGroup.id] : [],
            onChange: (_, rows) => setCurrentSettingGroup(rows[0]),
          }}
        />
      }
      rightContent={
        <>
          <ProTable<API.ISetting>
            columns={columns}
            actionRef={actionRef}
            request={async (params) => {
              const { data } = await pageSettingAPI({
                ...params,
                groupId: currentSettingGroup?.id || -1,
              });
              return data;
            }}
            rowKey="id"
            search={{
              labelWidth: 'auto',
              span: 6,
              filterType: 'light',
            }}
            pagination={
              {
                pageSize: 10,
              } as any
            }
          />

          {currentSetting && (
            <SettingDetail
              data={currentSetting || {}}
              visible={detailVisible}
              onClose={() => setDetailVisible(false)}
            />
          )}
        </>
      }
    />
  );
};

export default SettingManager;
